package com.one.blocks.common.util;

import lombok.experimental.UtilityClass;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import static com.one.blocks.common.constant.CommonConstant.CHINA_ZONE_ID;
import static com.one.blocks.common.constant.CommonConstant.SYSTEM_ZONE_OFFSET;

/**
 * @author linfuxin Created on 2022-02-14 11:21:42
 */
@UtilityClass
public class LocalDateTimeUtil {

    /**
     * 日期转秒级时间戳
     *
     * @param localDateTime 日期
     * @return 秒级时间戳
     */
    public static Long datetimeToSecond(LocalDateTime localDateTime) {
        return localDateTime == null ? null : localDateTime.toInstant(SYSTEM_ZONE_OFFSET).getEpochSecond();
    }

    /**
     * 时间戳转日期
     *
     * @param epochSecond 秒级时间戳
     * @return 日期
     */
    public static LocalDateTime secondToDatetime(Long epochSecond) {
        return epochSecond == null ? null : LocalDateTime.ofEpochSecond(epochSecond, 0, SYSTEM_ZONE_OFFSET);
    }

    /**
     * 日期转毫秒级时间戳
     *
     * @param localDateTime 日期
     * @return 毫秒级时间戳
     */
    public static Long datetimeToMills(LocalDateTime localDateTime) {
        return localDateTime == null ? null : localDateTime.toInstant(SYSTEM_ZONE_OFFSET).toEpochMilli();
    }

    /**
     * 时间戳转日期
     *
     * @param epochMilli 毫秒级时间戳
     * @return 日期
     */
    public static LocalDateTime millsToDatetime(Long epochMilli) {
        return epochMilli == null ? null : Instant.ofEpochMilli(epochMilli).atZone(SYSTEM_ZONE_OFFSET).toLocalDateTime();
    }

    public static java.sql.Date datetimeToSqlDate(LocalDateTime localDateTime) {
        return datetimeToSqlDate(localDateTime, CHINA_ZONE_ID);
    }

    public static java.sql.Date datetimeToSqlDate(LocalDateTime localDateTime, ZoneId zoneId) {
        return new java.sql.Date(localDateTime.atZone(zoneId).toInstant().toEpochMilli());
    }
}